package code1.binary_tree;

/**
 * 原题链接：https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-search-tree/
 */
public class P235 {

    //通用方法
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root==null || root==p || root==q){
            return root;
        }
        TreeNode left=lowestCommonAncestor(root.left,p,q);
        TreeNode right=lowestCommonAncestor(root.right,p,q);
        if(left!=null && right!=null){
            return root;
        }else if(left!=null && right==null){
            return left;
        }else if(left==null && right!=null){
            return right;
        }else{
            return null;
        }
    }

    //利用二叉排序树的性质: pq最近公共邻祖先之上的节点要么比pq都大、要么比pq都小
    public TreeNode lowestCommonAncestor2(TreeNode root, TreeNode p, TreeNode q) {
        if(root==null){
            return null;
        }
        if(root.val>p.val && root.val>q.val){       //当前节点值比p、q更大，往左搜
            TreeNode left = lowestCommonAncestor2(root.left, p, q);
            if(left!=null){
                return left;
            }
        }else if(root.val<p.val && root.val<q.val){       //当前节点值比p、q更小，往右搜
            TreeNode right = lowestCommonAncestor2(root.right, p, q);
            if(right!=null){
                return right;
            }
        }else{                                //当前节点的值在p、q之间，说明就是最近公共邻祖先
            return root;
        }
        return root;
    }
}
